#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import codecs
import configparser
from configparser import NoSectionError


class ReadBaseConfig:
    def __init__(self):
        # 拿到配置文件的根路径
        current_dir = os.path.abspath(os.path.dirname(__file__))
        config_path = os.path.join(os.path.dirname(current_dir), "base_config.ini")

        fd = open(config_path, encoding="utf-8")
        data = fd.read()

        if data[:3] == codecs.BOM_UTF8:
            data = data[3:]
            file = codecs.open(config_path, "w")
            file.write(data)
            file.close()
        fd.close()

        self.cf = configparser.ConfigParser()
        self.cf.read(config_path, encoding="utf-8")

    def get(self, config_title, config_name):
        """
        根据配置项+配置名获得配置值
        :param config_title:
        :param config_name:
        :return:
        """
        if type(config_title) == str and type(config_name) == str:
            try:
                value = self.cf.get(config_title, config_name)
            except NoSectionError as msg:
                raise ValueError('找不到[config_title]或[config_name]' + str(msg))
            return value
        else:
            raise TypeError("传入参数类型不正确")


if __name__ == "__main__":
    R = ReadBaseConfig()
    database_name = R.get('configuration', 'use_database_config')
    print(type(database_name))
    print(database_name)
    port = R.get(database_name, "port")
    print(type(port))
